package com.blyat.xsoft.auth.security;

import com.blyat.xsoft.auth.restful.entity.Authority;
import com.blyat.xsoft.auth.restful.entity.Client;
import com.blyat.xsoft.auth.restful.service.AuthorityService;
import com.blyat.xsoft.auth.restful.service.ClientService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;

import java.util.List;
import java.util.Objects;

/**
 * @Auther: syh
 * @Date: 2020/8/26
 * @Description:
 */
public class SecurityClientService implements ClientDetailsService {

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private ClientService clientService;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        Client client = clientService.getClientById(clientId);
        if (!Objects.isNull(client)) {
            List<Authority> authorityList = authorityService.getByClientId(clientId);
            if (!Objects.isNull(authorityList) && !authorityList.isEmpty()) {
                List<GrantedAuthority> grantedAuthorities = Lists.newArrayListWithExpectedSize(authorityList.size());
                authorityList.forEach(authority -> {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                            String.format("%s_%s", Constants.SECURITY_AUTH_PREFIX, authority.getId())
                    );
                    grantedAuthorities.add(grantedAuthority);
                });
                // 平台用户最基本角色
                grantedAuthorities.add(Constants.BASIC_GRANTED_AUTHORITY);
                client.setAuthorities(grantedAuthorities);
            }
            return client;
        } else {
            throw new NoSuchClientException("No client width requested id: " + clientId);
        }
    }
}
